package com.rmondjone.utils;

import android.os.Build;
import android.view.Window;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * @author ljq 2018.04.10
 */
public class XiaoMiStatusBarUtils {

    private static Class sXMLayoutParams;
    private static Field sXMDarkField;
    private static Method sXMDarkModeFlag;

    static {
        try {
            sXMLayoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            sXMDarkField = sXMLayoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            sXMDarkField.setAccessible(true);
            sXMDarkModeFlag = Window.class.getMethod("setExtraFlags", int.class, int.class);
        } catch (Exception e) {
            // no-op
        }
    }

    /**
     * 设置状态栏字体图标为深色，需要MIUIV6以上
     *
     * @param window 需要设置的窗口
     * @param dark   是否把状态栏字体及图标颜色设置为深色
     */
    public static boolean setMiuiStatusBarMode(Window window, boolean dark) {
        if (sXMDarkField == null || sXMDarkModeFlag == null || sXMLayoutParams == null || window == null) {
            return false;
        }
        try {
            int darkModeFlag = sXMDarkField.getInt(sXMLayoutParams);
            sXMDarkModeFlag.invoke(window, dark ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            // no-op
        }
        return false;
    }

    public static boolean isMiuiDevice() {
        return Build.MANUFACTURER.equals("Xiaomi");
    }
}
